import os
import sys

sys.path.append(os.path.join(os.getcwd(), 'third_party'))
# Closure Linter assumes it can import gflags.py
sys.path.append(os.path.join(os.getcwd(), 'third_party/gflags'))

from closure_linter import checker
from closure_linter import errors
from closure_linter.common import errorhandler

import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

import jsonerror

_DEBUG_JS = False

class MainHandler(webapp.RequestHandler):
  def get(self):

    template_dict = {
      'debug_js': _DEBUG_JS
    }

    response = template.render('templates/index.tpl', template_dict)
    self.response.out.write(response)


class LintHandler(webapp.RequestHandler):

  def post(self):

    runner = checker.GJsLintRunner()
    source = self.request.get('source')

    error_handler = jsonerror.JsonErrorHandler()
    js_style_checker = checker.JavaScriptStyleChecker(error_handler)
    js_style_checker.Check(filename='uploadedfile.js', source=source)

    self.response.out.write(simplejson.dumps(error_handler.GetJson()))

      
def main():
  application = webapp.WSGIApplication([
      ('/', MainHandler),
      ('/lint', LintHandler)],
      debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
